package com.enseirb.bdxmap.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.enseirb.bdxmap.dao.dto.UserMarkerDTO;
import com.enseirb.bdxmap.database.UserDatabaseHelper;

public class UserMarkerDAO implements MarkerDAO {
	private SQLiteDatabase		database;
	private UserDatabaseHelper	dbHelper;

	public UserMarkerDAO(Context context) {
		dbHelper = new UserDatabaseHelper(context);
	}

	public void open() {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public void createMarker(UserMarkerDTO marker) {
		ContentValues values = new ContentValues();
		values.put(UserDatabaseHelper.COL_LAT,		marker.latitude);
		values.put(UserDatabaseHelper.COL_LON,		marker.longitude);
		values.put(UserDatabaseHelper.COL_NAME,		marker.name);
		values.put(UserDatabaseHelper.COL_DESCR,	marker.description);
		this.open();
		database.insert(UserDatabaseHelper.TABLE_USER, null, values);
		this.close();
	}

	public List<UserMarkerDTO> getData() {
		List<UserMarkerDTO> markers = new ArrayList<UserMarkerDTO>();

		this.open();
		Cursor cursor = database.query(UserDatabaseHelper.TABLE_USER, UserDatabaseHelper.COL_ALL, null, null, null, null, null);
		
		cursor.moveToFirst();
		
		while (!cursor.isAfterLast()) {
			markers.add(cursorToMarker(cursor));
			cursor.moveToNext();
		}
		
		cursor.close();
		this.close();
		
		return markers;
	}
	
	private UserMarkerDTO cursorToMarker(Cursor cursor) {
		UserMarkerDTO marker = new UserMarkerDTO();
		marker.id			= String.valueOf(cursor.getInt(0));
		marker.latitude		= String.valueOf(cursor.getFloat(1));
		marker.longitude	= String.valueOf(cursor.getFloat(2));
		marker.name			= cursor.getString(3);
		marker.description	= cursor.getString(4);
	    return marker;
	  }
}
